package com.whiteape.book.core.parser;

import com.whiteape.book.core.manager.ParserManager;
import com.whiteape.book.model.bo.CategoryDetailBo;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.SiteSourceBean;
import com.whiteape.book.model.dto.SiteSourceCategoryBean;
import com.whiteape.book.model.dto.SiteSourceCategoryRuleBean;
import com.whiteape.book.model.dto.SiteSourceCategoryRuleResultBean;
import com.whiteape.book.utils.URLUtils;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Single;

/**
 * 分类的parser,各种排行啊，分类啊之类的
 */
public class CategoryParser {
    public static Single<List<CategoryDetailBo>> parse(SiteSourceBean siteSourceBean, SiteSourceCategoryBean categoryBean, String currentUrl, String html) {

        List<CategoryDetailBo> searchResultBoList = new ArrayList<>();
        if (siteSourceBean == null || StringUtils.isEmpty(html)) {
            return Single.create(emitter -> emitter.onSuccess(searchResultBoList));
        }
        return Single.create(emitter -> {

            try {
                //TODO search rule需要校验有值的：detailUrl, title, author,不合格的不入库
                SiteSourceCategoryRuleResultBean categoryInfoBean = siteSourceBean.getSiteCategory().getResult();
                String listRule = categoryInfoBean.getList();

                //TODO 认定取list的都只有一个？
                List list = ParserManager.getElementList(currentUrl, html, listRule);
                if (list == null || list.size() == 0) {
//                emitter.onError(new Throwable("list not found"));
                    //可能只有一条，直接跳转到书籍详情页面了,在这里做判断

                    //TODO如果直接到详情页的，其实可能同时拿到章节信息，加快下一步点击进入详情的速度
//                boolean parseCatalogTogether = StringUtils.isEmpty(siteSourceBean.getMediaInfoDetailRule().getCatalogUrl());
//                    parseMediaInfoDetail(siteSourceBean, searchResultBoList, currentUrl, html);

                    emitter.onSuccess(searchResultBoList);
                    return;
                }

                HashMap<String, String> varMap = categoryBean.getVarMap();
                if (varMap == null) {
                    varMap = new HashMap<>();
                    categoryBean.setVarMap(varMap);
                }
                if(!StringUtils.isEmpty(categoryInfoBean.getPageTotal())) {
                    //注意，这里用的是全部网页的html，而不是当前Item的doc
                    String pageTotalStr = ParserManager.parseOne(currentUrl, html, categoryInfoBean.getPageTotal(), varMap);
                    int pageTotal = 0;
                    try {
                        pageTotal = Integer.parseInt(pageTotalStr);
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                    int nextPageInt = 0;
                    //有pageTotal，可能会用到page
                    String currentPageStr = "1";
                    if (varMap.containsKey("page")) {
                        currentPageStr = varMap.get("page");
                    }
                    if (!StringUtils.isEmpty(currentPageStr)) {
                        int currentPageInt = Integer.parseInt(currentPageStr);
                        if (currentPageInt < pageTotal) {
                            nextPageInt = currentPageInt + 1;
                        }
                    }
                    varMap.put("page", "" + nextPageInt);
                }
                for (Object ele : list) {

                    String doc = ParserManager.getElementString(ele);

                    CategoryDetailBo infoBean = new CategoryDetailBo();
                    infoBean.setVarMap(varMap);
                    infoBean.setCategoryUrl(currentUrl);
                    infoBean.setCategoryBean(categoryBean);
                    String detailRule = categoryInfoBean.getDetailUrl();
                    //TODO text or attr?
                    String detailUrl = ParserManager.parseOne(currentUrl, doc, detailRule, varMap);
                    if (StringUtils.isEmpty(detailUrl)) {
                        continue;
                    }
                    String categoryUrl = siteSourceBean.getSiteCategory().getUrl();
                    if (!categoryUrl.startsWith("http")) {
                        categoryUrl = URLUtils.getAbsolutePath(siteSourceBean.getSiteHostUrl(), categoryUrl);
                        siteSourceBean.getSearch().setUrl(categoryUrl);
                    }
                    detailUrl = URLUtils.getAbsolutePath(categoryUrl, detailUrl);
                    infoBean.setDetailUrl(detailUrl);

                    ///////author
                    String authorRule = categoryInfoBean.getAuthor();
                    String author = ParserManager.parseOne(currentUrl, doc, authorRule, varMap);
                    infoBean.setAuthor(author);

                    ///title
                    String titleRule = categoryInfoBean.getTitle();
                    String title = ParserManager.parseOne(currentUrl, doc, titleRule, varMap);
                    if (StringUtils.isEmpty(title)) {
                        continue;
                    }
                    infoBean.setTitle(title);

                    String coverUrl = ParserManager.parseOne(currentUrl, doc, categoryInfoBean.getCoverUrl(), varMap);
                    if (!coverUrl.isEmpty()) {
                        coverUrl = URLUtils.getAbsolutePath(currentUrl, coverUrl);
                    }
                    infoBean.setCoverUrl(coverUrl);
                    ///.........others
                    infoBean.setMediaType(siteSourceBean.getSiteType());
                    infoBean.setCategory(ParserManager.parseOne(currentUrl, doc, categoryInfoBean.getCategory(), varMap));
                    infoBean.setDesc(ParserManager.parseOne(currentUrl, doc, categoryInfoBean.getDesc(), varMap));
                    infoBean.setLastChapter(ParserManager.parseOne(currentUrl, doc, categoryInfoBean.getLastChapter(), varMap));
                    infoBean.setLastUpdated(ParserManager.parseOne(currentUrl, doc, categoryInfoBean.getLastUpdated(), varMap));
                    infoBean.setState(ParserManager.parseOne(currentUrl, doc, categoryInfoBean.getState(), varMap));
                    infoBean.setWordCount(ParserManager.parseOne(currentUrl, doc, categoryInfoBean.getWordCount(), varMap));

                    String nextPage = ParserManager.parseOne(currentUrl, html, categoryInfoBean.getNextPage(), varMap);
                    if (!StringUtils.isEmpty(nextPage)) {
                        nextPage = URLUtils.getAbsolutePath(currentUrl, nextPage);
                    }
                    infoBean.setNextPage(nextPage);


                    //next page : xxxxxxx/{{$page}}/fff
                    //1.根据当前url算出page
                    //2.根据pTotal，算出是否还有next page,填充到page
                    //3.生成新的page url

                    infoBean.setSiteSourceBean(siteSourceBean);

                    searchResultBoList.add(infoBean);

                }

                emitter.onSuccess(searchResultBoList);
//            emitter.onComplete();
            } catch (Exception e) {
                e.printStackTrace();
                emitter.onSuccess(searchResultBoList);
            }

        });


    }


    public static Single<Map<SiteSourceBean, List<SiteSourceCategoryBean>>> parseCategoryIndex(SiteSourceBean siteSourceBean, String currentUrl, final String rawHtml) {
        Map<SiteSourceBean, List<SiteSourceCategoryBean>> result = new HashMap();
        List<SiteSourceCategoryBean> categoryBeanList = new ArrayList<>();
        SiteSourceCategoryRuleBean categoryIndexRuleBean = siteSourceBean.getSiteCategory();
        return Single.create(emitter -> {

            String html = rawHtml;
//            try {
//                String charset = siteSourceBean.getSiteCategory().getCharset();
//                if (!StringUtils.isEmpty(charset)) {
//                    html = new String(rawHtml.getBytes(), charset);
//                }
//            }catch (Exception e){
//                e.printStackTrace();
//            }
            try {
                String listRule = categoryIndexRuleBean.getCategoryList();

                //TODO 认定取list的都只有一个？
                List list = ParserManager.getElementList(currentUrl, html, listRule);
                if (list == null || list.size() == 0) {
                    emitter.onSuccess(result);
                    return;
                }
                for (Object ele : list) {
                    SiteSourceCategoryBean siteSourceCategory = new SiteSourceCategoryBean();
                    String doc = ParserManager.getElementString(ele);
                    HashMap<String, String> varMap = new HashMap<>();
                    siteSourceCategory.setSiteHostUrl(siteSourceBean.getSiteHostUrl());
                    siteSourceCategory.setCategoryUrl(URLUtils.getAbsolutePath(siteSourceBean.getSiteHostUrl(), ParserManager.parseOne(currentUrl, doc, categoryIndexRuleBean.getCategoryUrl(), varMap)));
                    siteSourceCategory.setCategoryName(ParserManager.parseOne(currentUrl, doc, categoryIndexRuleBean.getCategoryName(), varMap));
                    categoryBeanList.add(siteSourceCategory);
                }
                result.put(siteSourceBean, categoryBeanList);
                emitter.onSuccess(result);
            } catch (Exception e) {
                emitter.onError(e);
            }

        });

    }

}
